package Internet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.URLPermission;

//回响服务器
public class UdpEchoServer1 {

    private DatagramSocket socket = null;

    public UdpEchoServer1(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        while (true) {
        //接收数据
        DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
        socket.receive(requestPacket);

        //将数据转化为字符串
        String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

        //计算响应
        String response = process(request);

        //将响应返回给客户端
        DatagramPacket responsePocket = new DatagramPacket(response.getBytes(),
                0, response.getBytes().length, requestPacket.getSocketAddress());
        socket.send(responsePocket);

        //打印日志
        System.out.printf("[%s, %s], request : %s, response : %s",
                responsePocket.getAddress().toString(), responsePocket.getPort(), request, response);
        }
    }

    //计算响应
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
